import './css/index.css';
import { Form, Input, Button, message } from 'antd';
import { useState, useRef } from "react";
import { LoginAsync } from '../../api/Login';
import { useNavigate } from 'react-router-dom';
const Login = () => {
    const [form, setForm] = useState({
        username: '',
        password: ''
    });

    const navigate = useNavigate();

    const formRef = useRef(null)
    const handleChange = (e) => {
        const { name, value } = e.target;
        setForm(prevForm => ({
            ...prevForm,
            [name]: value
        }));
    };

    const submit = async () => {
        try {
            const res = await LoginAsync(form)
            if (res.code === 200) {
                message.success('登录成功')
                sessionStorage.setItem('token', res.token)
                sessionStorage.setItem('userinfo', JSON.stringify(res.user))
                navigate('/')
            } else {
                message.error(res.msg)
            }
        } catch (err) {
            message.error(err)
        }
    }

    return (
        <div className='login-container'>
            <div className='content'>
                <h1 className='title'>登录</h1>
                <Form ref={formRef}>
                    <Form.Item name="username"
                        rules={[
                            { required: true, message: '请输入账号' },
                        ]} validateTrigger="onBlur">
                        <Input
                            name="username"
                            value={form.username}
                            size="large"
                            placeholder="请输入账号"
                            onChange={handleChange}
                            allowClear
                        />
                    </Form.Item>
                    <Form.Item name="password"
                        rules={[
                            { required: true, message: '请输入密码' },
                        ]} validateTrigger="onBlur">
                        <Input.Password
                            name="password"
                            size="large"
                            value={form.password}
                            placeholder="请输入密码"
                            onChange={handleChange}
                            allowClear
                        />
                    </Form.Item>
                </Form>
                <Button onClick={submit} size="large" type="primary" className='login-btn'>登录</Button>
            </div>
        </div>
    );
}
export default Login;